//
//  BindViewController.m
//  Ikinloop-demo
//
//  Created by Li Shen on 2021/4/20.
//  Copyright © 2021 lyh. All rights reserved.
//

#import "EcgDeviceScanViewController.h"
#import "BlindingDeviceView.h"
#import "DiscoverDeviceView.h"
#import "BlindFailView.h"
#import "BlindSuccessView.h"
#import "NoBlindingWithDeviceView.h"
#import <IKLibrary/IKLibrary.h>
#import "EcgCheckOrBindController.h"
#import "IKAudioManager.h"


@interface EcgDeviceScanViewController ()<NoBlindingWithDeviceDelegate,BlindingDeviceViewDelegate,BlindFailViewDelegate,DiscoverDeviceViewDelegate,IIKEcgStateEvent,IIKEcgDeviceScanEvent>

@property (nonatomic,strong)dispatch_source_t scanTimer;

@property (nonatomic,strong)BlindingDeviceView *blindView;
@property (nonatomic,strong)NoBlindingWithDeviceView *noblingView;

//发现界面
@property (nonatomic,strong)DiscoverDeviceView *discoverView;
//失败的界面
@property (nonatomic,strong)BlindFailView *failView;
//成功绑定
@property (nonatomic,strong)BlindSuccessView *successView;
//显示界面
@property (nonatomic,assign)viewType viewType;
//是否可以播放语音
@property (nonatomic,assign)BOOL canpaly;
//是否可以toast
@property (nonatomic,assign)BOOL canToast;

@property (nonatomic,strong)NSTimer *timer;

@property (nonatomic,assign)BOOL isvable;
@property (nonatomic,assign)FailType failType;

@property (nonatomic, strong) NSString *deviceId;

@property (nonatomic, strong) IKAudioManager *audioManager;
@end

@implementation EcgDeviceScanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"绑定设备";
    self.view.backgroundColor = [UIColor whiteColor];
//    self.edgesForExtendedLayout = UIRectEdgeNone;
    [self setUpUI];
    self.audioManager = [[IKAudioManager alloc] init];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[IKEcgCheck getInstance] IKInit];
    [[IKEcgCheck getInstance] IKRegistEcgDeviceScanEvent:self];
    [[IKEcgCheck getInstance] IKRegistEcgStateEvent:self andUserData:nil];
    [self showViewWithType:viewTypeUnblind];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.audioManager stopAllVoice];
    [self stopSearch];
    [[IKEcgCheck getInstance] IKUninit];
}

-(void)setUpUI
{
    [self.view addSubview:self.noblingView];
    [self.view addSubview:self.blindView];
    [self.view addSubview:self.failView];
    [self.view addSubview:self.discoverView];
}

-(void)showViewWithType:(viewType)viewtype
{
    self.viewType = viewtype;
    self.canToast = NO;
    self.canpaly = NO;

    [self.view.subviews makeObjectsPerformSelector:@selector(removeFromSuperview) withObject:nil];
    switch (viewtype) {
        case viewTypeUnblind:
        {
            [self.view addSubview:self.noblingView];
            
            self.canToast = YES;
            break;
        }
        case viewTypeSearch:
        {
            self.canpaly = YES;
            [self.view addSubview:self.blindView];
            break;
        }
        case viewTypeFound:
            [self.view addSubview:self.discoverView];
            break;
        case viewTypeFail:
            [self.view addSubview:self.failView];
            break;
        case viewTypeSuccess:
            [self.view addSubview:self.successView];
            break;
        default:
            break;
    }
}

-(void)startSearch
{
    [self.blindView rotationanimation];
    [self startTimer];
    
    [[IKEcgCheck getInstance] IKStartEcgDeviceScan];
    
}

- (void)stopSearch{
    [[IKEcgCheck getInstance] IKStopEcgDeviceScan];
    
}

-(void)startTimer
{
    [self.timer invalidate];
    self.timer = nil;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(cancelTimer) userInfo:nil repeats:NO];
}

-(void)cancelTimer
{
    [self.timer invalidate];
    self.timer = nil;
    if (self.isvable) {
        return;
    }
    //显示失败界面
    self.failType = FailTypeNotFound;
    [self showViewWithType:viewTypeFail];
    [self swichType:self.failType];
    [self stopSearch];
}


#pragma mark - 懒加载
-(NoBlindingWithDeviceView *)noblingView
{
    if (!_noblingView)
    {
        _noblingView = [[NoBlindingWithDeviceView alloc] initWithFrame:self.view.frame];
        _noblingView.delegate = self;
    }
    return _noblingView;
}

-(BlindingDeviceView *)blindView
{
    if (!_blindView)
    {
        _blindView = [[BlindingDeviceView alloc] initWithFrame:self.view.frame];
        _blindView.delegate = self;
    }
    return _blindView;
}

-(BlindFailView *)failView
{
    if (!_failView)
    {
        _failView = [[BlindFailView alloc] initWithFrame:self.view.frame];
        _failView.delegate = self;
    }
    return _failView;
}

-(DiscoverDeviceView *)discoverView
{
    if (!_discoverView)
    {
        _discoverView = [[DiscoverDeviceView alloc] initWithFrame:self.view.frame];
        _discoverView.delegate = self;
    }
    return _discoverView;
}

-(BlindSuccessView *)successView
{
    if (!_successView)
    {
        _successView = [[BlindSuccessView alloc] initWithFrame:self.view.frame];
    }
    return _successView;
}

//错误显示文本
-(void)swichType:(FailType)type
{
    switch (type)
    {
        case FailTypeNotOpenNet:
            [self.failView setOneTitle:INTERNATIONAL(@"string_device_network_faild") andTitleTwo:@"" andTitle:INTERNATIONAL(@"string_device_cannot_bond")];
            break;
        case FailTypeAlreadyBlind:
            [self.failView setOneTitle:INTERNATIONAL(@"string_bond_faild_alreadybond") andTitleTwo:@"" andTitle:INTERNATIONAL(@"string_device_cannot_bond")];
            break;
        case FailTypeAccountAlreadyBlind:
            [self.failView setOneTitle:INTERNATIONAL(@"string_bond_faild_user_have_bondeddevice") andTitleTwo:@"" andTitle:INTERNATIONAL(@"string_device_cannot_bond")];
            break;
        case FailTypeNotFound:
            [self.failView setOneTitle:INTERNATIONAL(@"string_bond_faild_reason") andTitleTwo:@"" andTitle:INTERNATIONAL(@"string_device_bond_faild")];
            break;
        case FailTypeTimeout:
            [self.failView  setOneTitle:INTERNATIONAL(@"string_device_network_faild") andTitleTwo:@"" andTitle:INTERNATIONAL(@"string_device_cannot_bond")];
            break;
        case FailTypeOtherError:
            [self.failView  setOneTitle:INTERNATIONAL(@"string_bond_faild_reason") andTitleTwo:@"" andTitle:INTERNATIONAL(@"string_bond_faild_default")];
            break;
        case FailTypeTokenError:
            [self.failView  setOneTitle:INTERNATIONAL(@"string_bond_faild_token_error") andTitleTwo:@"" andTitle:INTERNATIONAL(@"string_device_cannot_bond")];
            break;
        default:
            break;
    }
}

- (void)runCheck{
    EcgCheckOrBindController *vc =  (EcgCheckOrBindController*)self.parentViewController;
    [vc showEcgView];
}

#pragma mark - 绑定设备页面回调(点击开始绑定按钮)
-(void)callbackgoBlinding
{
    NSLog(@"callbackgoBlinding");
    [self showViewWithType:viewTypeSearch];
    [self.audioManager playPressBtn];
    [self startSearch];
}

#pragma mark - 绑定中回调
-(void)callbacknoBlinding
{
    [self showViewWithType:viewTypeSearch];
}

#pragma mark - 发现设备
-(void)callbackdonext
{
    self.isvable = YES;
    [self showViewWithType:viewTypeSuccess];
    self.successView.deviceString = self.deviceId;
    
     //先绑定在本地中
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:self.deviceId forKey:@"key_deviceId"];
    [userDefaults synchronize];
    [self.successView connectSuccess];
    [self.audioManager playerBindSuccess];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self performSelector:@selector(runCheck) withObject:nil afterDelay:4];
    });
}


-(void)callbackBack
{
    self.isvable = NO;
    [self showViewWithType:viewTypeSearch];
    [self startSearch];
}

-(void)callbackreblindDevice{
    [self showViewWithType:viewTypeSearch];
    [self startSearch];
}

#pragma  mark - 扫描回调
-(void)OnEcgScanDeviceDataDeviceId:(NSString *)deviceId deviceName:(NSString *)deviceName{
    NSLog(@"OnEcgScanDeviceDataDeviceId--%@",deviceId);
    self.deviceId = deviceId;
    [self.timer invalidate];
    self.timer = nil;
    [self stopSearch];
    self.discoverView.deviceID = deviceId;
    
    [IKPublicUtil runOnMainThread:^{
        [self showViewWithType:viewTypeFound];
    }];
    
}

- (void)OnReciveEcgState:(EcgState)state Desc:(NSString *)desc andUserdata:(id)userdata{
    NSLog(@"state------%@",desc);
}
- (void)dealloc{
    
}
@end
